package com.itheima.controller;


import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.HealthManager;
import com.itheima.pojo.Member;
import com.itheima.pojo.Setmeal;
import com.itheima.service.MemberService;
import com.itheima.service.SetmealService;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/member")
public class MemberController {
    @Reference
    private MemberService memberService;
    @Reference
    private SetmealService setmealService;

    /**
     * 初始化时查询分页方法
     *
     * @param queryPageBean
     * @return pageResult
     */
    @RequestMapping("/findPage")
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean) {
        PageResult pageResult = memberService.findPage(queryPageBean);
        return pageResult;
    }

    //添加会员
    @RequestMapping("/add")
    public Result add(@RequestBody Member member) {
        try {
            memberService.backendAdd(member);
            return new Result(true, MessageConstant.ADD_MEMBER_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.ADD_MEMBER_FAIL);
        }
    }

    //删除会员
    @RequestMapping("/delete")
    public Result delete(Integer id) {
        try {
            memberService.deleteById(id);
            return new Result(true, MessageConstant.DELETE_MEMBER_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.DELETE_MEMBER_FAIL);
        }
    }

    //编辑会员
    @RequestMapping("/edit")
    public Result edit(@RequestBody Member member) {
        try {
            memberService.editMember(member);
            return new Result(true, MessageConstant.EDIT_MEMBER_SUCCESS);

        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.EDIT_MEMBER_FAIL);
        }

    }

    //根据id查询会员
    @RequestMapping("/findById")
    public Result findById(Integer id) {
        try {
            Member member = memberService.findById(id);
            return new Result(true, MessageConstant.EDIT_MEMBER_SUCCESS, member);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.SELELT_FAIL);
        }
    }

    //查询所有健康管理师信息
    @RequestMapping("/findDate")
    public Result findDate() {
        List<HealthManager> list = memberService.findDate();
        return new Result(true, MessageConstant.EDIT_MEMBER_SUCCESS, list);
    }

    @RequestMapping("/export")
    public Result export(Integer[] ids, HttpServletRequest request, HttpServletResponse response) {
        try {
            if (ids != null && ids.length > 0) {
                List<Map> list = memberService.getReportData(ids);
                for (int i = 0; i < list.size(); i++) {
                    Map map = list.get(i);
                    String name = (String) map.get("name");
                    String sex = (String) map.get("sex");
                    String phoneNumber = (String) map.get("phoneNumber");
                    List address = (List) map.get("address");
                    List setmealName = (List) map.get("setmealName");
                    List checkGroupName = (List) map.get("checkGroupName");
                    List checkItemName = (List) map.get("checkItemName");
//                    System.out.println(address);
//                    System.out.println(setmealName);
//                    System.out.println(checkGroupName);
                    String filePath = request.getSession().getServletContext().getRealPath("template") + File.separator + "health.xlsx";
                    //基于提供的Excel模板文件在内存中创建一个Excel表格对象
                    XSSFWorkbook excel = new XSSFWorkbook(new FileInputStream(new File(filePath)));
                    //读取第一个工作表
                    XSSFSheet sheet = excel.getSheetAt(0);

                    XSSFRow row = sheet.getRow(1 + i);
                    row.getCell(i).setCellValue(name);   //会员名字
                    row.getCell(1 + i).setCellValue(sex);//会员性别
                    row.getCell(2 + i).setCellValue(phoneNumber);//会员手机号码

                        for (Object o : address) {
                            String string = o.toString();
                            row.getCell(3 + i).setCellValue(string);
                    }
                    for (Object j : setmealName) {
                        String string = j.toString();
                        row.getCell(4 + i).setCellValue(string);//套餐名字
                    }
                    for (Object b : checkGroupName) {
                        String string = b.toString();
                        row.getCell(5 + i).setCellValue(string);//检查组名字
                    }
                    for (Object k : checkItemName) {
                        String string = k.toString();
                        row.getCell(6 + i).setCellValue(string);//检查项名字
                    }
                    //使用输出流进行表格下载,基于浏览器作为客户端下载
                    OutputStream out = response.getOutputStream();
                    response.setContentType("application/vnd.ms-excel");//代表的是Excel文件类型
                    response.setHeader("content-Disposition", "attachment;filename=report.xlsx");//指定以附件形式进行下载
                    excel.write(out);
                    out.flush();
                    out.close();
                    excel.close();
                }
                return new Result(true, MessageConstant.GET_BUSINESS_REPORT_SUCCESS);
            } else {
                response.getWriter().write("请选择导出的信息框");
                request.getRequestDispatcher("/pages/member.html").forward(request, response);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new Result(false, MessageConstant.GET_BUSINESS_REPORT_FAIL);
    }
}
